package com.wjs.CarolSecKill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wjs.CarolSecKill.pojo.Order;
import com.wjs.CarolSecKill.pojo.SeckillOrder;
import com.wjs.CarolSecKill.pojo.User;
import com.wjs.CarolSecKill.service.IGoodsService;
import com.wjs.CarolSecKill.service.IOrderService;
import com.wjs.CarolSecKill.service.ISeckillOrderService;
import com.wjs.CarolSecKill.service.IUserService;
import com.wjs.CarolSecKill.vo.GoodsVo;
import com.wjs.CarolSecKill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/seckill")
public class SecKillController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private IOrderService orderService;

    @PostMapping("/doSeckill")
    public String doSeckill(Model model, Long goodsId, @CookieValue("userTicket")String ticket,
                            HttpServletRequest request,
                            HttpServletResponse response){
        if(StringUtils.isEmpty(ticket)){
            return "login";
        }
        User user = userService.getUserByTicket(ticket, request, response);
        if(user==null){
            return "login";
        }
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        //判断库存
        if(goodsVo.getStockCount()<1){
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
            return "secKillFail";
        }
        //判断是否重复购买
        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().
                eq("goods_id", goodsId).eq("user_id", user.getId()));
        if(seckillOrder!=null){
            model.addAttribute("errmsg",RespBeanEnum.REPEATE_ERROR.getMessage());
            return "secKillFail";
        }
        Order order=orderService.doSecKill(user,goodsVo);
        model.addAttribute("order",order);
        model.addAttribute("goods",goodsVo);
        return "orderDetail";
    }
}
